﻿using BenchmarkDotNet.Attributes;
using NLua;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace NLuaBenchmarkDotNetTest
{
    [MemoryDiagnoser]
    public class AtBenchmarks
    {
        private Lua _lua;
        private double[] _data = new double[1000];

        [GlobalSetup]
        public void Setup()
        {
            _lua = new Lua();
            // 加载自定义文件
            string binDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string fullFileName = Path.Combine(binDirectory, "Lua");
            LoadScriptsFromDirectory(fullFileName);
            new LuaBinder().Bind(_lua);

            // 创建测试数据（1000元素数组）
            for (int i = 0; i < 1000; i++)
            {
                _data[i] = i;
            }
            _lua["data"] = _data;

        }
        /// <summary>
        /// 加载并执行指定目录下的所有 Lua 文件
        /// </summary>
        private void LoadScriptsFromDirectory(string directoryPath)
        {
            foreach (var filePath in GetSysScriptFiles(directoryPath))
            {
                _lua.DoFile(filePath);
            }
        }
        public IEnumerable<string> GetSysScriptFiles(string rootPath, SearchOption searchOption = SearchOption.AllDirectories)
        {
            return Directory.EnumerateFiles(rootPath, "*.lua", searchOption);
        }
        [Benchmark]
        public object NativeLuaAt()
        { 
            return _lua.DoString("return At_Lua(data, 500)")[0];
        }


        [Benchmark]
        public object CSharpRegisterAt()
        {
            return _lua.DoString("return At(data, 500)")[0];
        }

        [Benchmark]
        public object NativeCSharpAt()
        {
            return MathUtils.At(_data,500);
        }

        [GlobalCleanup]
        public void Cleanup() => _lua.Dispose();
    }
}
